package net.easyjava.framework.web.security;

import net.easyjava.framework.web.constants.WebConstants;
import net.easyjava.tools.cookie.CookieTools;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wxnacy on 15/12/22.
 */
@Service
public class UserSecurityAdminCookie extends UserSecurity {
    public static final String USER_KEY = "A-U";

    protected static final long LONG_MAXAGE = 1000*60*60*24*30*12L;//cookie保存时间 一nian
    public static final long MAXAGE_30M = 1000*60*60*24L;//cookie保存时间 30分钟

    @Override
    public void setLongUserSecurityBean(HttpServletResponse response, String userId, String userIp) {
        this.setUserSecurityBean(response,userId,userIp,LONG_MAXAGE);
    }

    @Override
    public void setShortUserSecurityBean(HttpServletResponse response, String userId, String userIp, long maxAge) {
        this.setUserSecurityBean(response,userId,userIp,maxAge);
    }

    @Override
    protected void writeUserSecurity(HttpServletResponse response, String value, long maxAge) {
        CookieTools.setCookie(response,USER_KEY,value,(int)(maxAge/1000), WebConstants.DOMAIN);
    }

    @Override
    public void removeUserSecurity(HttpServletRequest request, HttpServletResponse response) {
        CookieTools.removeCookie(request,response,USER_KEY);
    }

    @Override
    protected String readUserSecurity(HttpServletRequest request) {
        Cookie user = CookieTools.getCookie(request,USER_KEY);
        if(user == null){
            logger.info("cookie 中没有 {} 值",USER_KEY);
            return null;
        }
        return user.getValue();
    }
}
